#!/usr/bin/python

#-*- coding:utf-8 -*-

__author__ = "Carlan Calazans <carlan@gmail.com>"
__version__ = "0.1"
__date__ = "Date: 17/3/2007"
__copyright__ = "Copyright (c) 2007 Carlan Calazans"
__license__ = "GPL"

import os
from ConfigParser import ConfigParser

class ToDoConfig:
    """
    System config class to write and read config file. Most of configuration
    is relative to database. This class only handle a single section.
    """
    def __init__(self, file):
        """
        Creates a ToDoConfig/ConfigParser instance.
        """
        #path to config
        self.file = file
        #config parser object
        self.config = ConfigParser()

    def setSection(self, section):
        """
        Add a new section to ConfigParser instance.
        """
        self.config.add_section(section)

    def getSection(self, section):
        """
        Return a section.
        """
        if section in self.config.sections() and len(self.config.sections()) == 1:
            return self.config.sections()[0]

    def hasSection(self, section):
        """
        Return if the ConfigParser instance has a section.
        """
        return self.config.has_section(section)
    
    def setKey(self, section, key, value):
        """
        Set a new key/value in ConfigParser instance.
        """
        self.config.set(self.getSection(section), key, value)
        
    def getKeyValue(self, section, key):
        """
        Return key value.
        """
        return self.config.get(self.getSection(section), key)
    
    def writeConfig(self):
        """
        Write config file.
        
        Example:
        
        toDoConfig = ToDoConfig("/tmp/temp.conf")
        #define section and options
        toDoConfig.setSection("ABC")
        toDoConfig.setKey("ABC", "key1", "value1")
        toDoConfig.setKey("ABC", "key2", "value2")
        toDoConfig.setKey("ABC", "key3", "value3")    
        #call method writeConfig
        toDoConfig.writeConfig()
        """
        arq = open(self.file, "w")
        self.config.write(arq)
        arq.close()

    def readConfig(self):
        """
        Read config file.
        
        Example:
        
        toDoConfig = ToDoConfig("/tmp/temp.conf")
        #call method readConfig
        toDoConfig.readConfig()
        #list something
        print "Section ABC exists?", toDoConfig.hasSection("ABC")
        print "Value of key1:", toDoConfig.getKeyValue("ABC", "key1")
        print "Value of key3:", toDoConfig.getKeyValue("ABC", "key3")
        print "Value of key2:", toDoConfig.getKeyValue("ABC", "key2")        
        """
        if os.path.exists(self.file):
            self.config.read(self.file)